/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: 2.c
> Author:cjy
> Mail: 
> Created Time: 2024年08月04日 星期日 14时41分14秒
***************************************************/
//用父子进程分别操作写同一个文件，父和子都给其中写10次当前时间。
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc,const char* argv[])
{
	pid_t pid = 0;
	int i = 0;
	int fp = 0;
	time_t t;
	struct tm *nowtime;
	char name[100] = {0};
        printf("请输入你想读取文件的位置与名字:");
        scanf("%s",name);
        // 打开文件
        fp = open(name,O_RDWR | O_APPEND | O_CREAT,0640);
        if(fp == -1) {
           perror("open");
           exit(-1);
        }
	pid = fork();
	if(pid == 0) 
	{
	int ret = 0;
	char time_now[50] = {0};
		while(i < 10)
		{
			printf("child1 procee:%d\n",getpid());
			time(&t);
			nowtime = localtime(&t);
			sprintf(time_now,"%02d:%02d:%02d\n", nowtime->tm_hour, nowtime->tm_min,nowtime->tm_sec);
			ret = write(fp,time_now,strlen(time_now));
			if(ret == -1)
        		{
            			perror("write");
            			close(fp);
            			exit(EXIT_FAILURE);
        		}
			//memset(time_now,0,sizeof(time_now));
			sleep(1);
			i++;
		}
		close(fp);
		exit(0);
	}else if(pid < 0)
	{
		printf("fork error\n");
	}
	int ret = 0;
	char time_now[50] = {0};
		while(i < 10)
		{
			printf("father process:%d\n",getpid());
			time(&t);
			nowtime = localtime(&t);
			sprintf(time_now,"%04d-%02d-%02d\n", nowtime->tm_year + 1900, nowtime->tm_mon + 1, nowtime->tm_mday);
			ret = write(fp,time_now,strlen(time_now));
			if(ret == -1)
        		{
            			perror("write");
            			close(fp);
            			exit(EXIT_FAILURE);
        		}
			//memset(time_now,0,sizeof(time_now));
			sleep(1);
			i = i + 1;
		}
close(fp);
wait(NULL);
return 0;
}
